package com.huoniu.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.huoniu.api.entity.Resource;
import com.huoniu.api.entity.RoleResource;
import com.huoniu.api.mapper.ResourceMapper;
import com.huoniu.api.mapper.RoleResourceMapper;
import com.huoniu.api.service.ResourceService;
import com.huoniu.api.service.RoleResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @类 名： ResourceServiceImpl <br/>
 * @描 述： <br/>
 * @日 期： 2020/9/11 10:22<br/>
 * @作 者： 侯建军<br/>
 * @版 本： 1.0.0
 * @since JDK 1.8
 */
@Service
public class ResourceServiceImpl implements ResourceService {
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private RoleResourceService resourceService;

    @Override
    public List<Resource> getMenuTree(Long roleId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if(StringUtils.isEmpty(roleId)){

        }else {
            List<RoleResource> roleResources = resourceService.getRoleResourceByRoleId(roleId);
            List<Long> resourceIds = new ArrayList<>();
            for (RoleResource roleResource : roleResources) {
                resourceIds.add(roleResource.getResourceId());
            }
            queryWrapper.in("id", resourceIds);
        }

        // 查询所有菜单
        List<Resource> parentList = resourceMapper.selectList(queryWrapper);
        List<Resource> resources = new ArrayList<>();
        for (Resource resource : parentList) {
            // 查找其子菜单
            if (resource.getParentId().equals(0L)) {
                List<Resource> resources1 = this.getChildren(resource, parentList);
                resource.setChildren(resources1);
                resources.add(resource);
            }
        }
        return resources;
    }

    public List<Resource> getChildren(Resource resource, List<Resource> resources) {
        List<Resource> list = new ArrayList<>();
        for (Resource resource0 : resources) {
            if (resource.getId().equals(resource0.getParentId())) {
                resource0.setChildren(getChildren(resource0, resources));
                list.add(resource0);
            }
        }
        return list;
    }
}
